package top.lixunda.ecommerce.server.auth.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * Http工具，用户发送请求
 *
 * @author Xumda
 * @deprecated 2019年12月17日14:30:59
 */
@SuppressWarnings("DeprecatedIsStillUsed")
@Slf4j
@Component
public class HttpUtil {

    /**
     * post请求
     *
     * @param url  请求地址
     * @param body 请求数据
     */
    @SuppressWarnings("Duplicates")
    public String post(String url, String body) {
        log.debug("post url = " + url + "\n" + "body = " + body);
        StringBuilder result = new StringBuilder();
        OutputStreamWriter out = null;
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            //设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(200000);

            //提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out.write(body);
            out.flush();

            //读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            //读取第一行的时候不加换行符
            boolean firstLine = true;
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    result.append(System.lineSeparator());
                }
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return result.toString();
    }
}
